import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import UserDashboard from '../views/user/UserDashboard.vue';
import DrugList from '../views/DrugList.vue';
import Cart from '../views/Cart.vue';
import OrderList from '../views/OrderList.vue';
import AdminLayout from '../views/admin/AdminLayout.vue';

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/dashboard',
    name: 'UserDashboard',
    component: UserDashboard,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'drugs',
        name: 'DrugList',
        component: DrugList
      },
      {
        path: 'cart',
        name: 'Cart',
        component: Cart
      },
      {
        path: 'orders',
        name: 'OrderList',
        component: OrderList
      }
    ]
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('../views/admin/Dashboard.vue')
      },
      {
        path: 'drugs',
        name: 'DrugManagement',
        component: () => import('../views/admin/DrugManagement.vue')
      },
      {
        path: 'orders',
        name: 'OrderManagement',
        component: () => import('../views/admin/OrderManagement.vue')
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('../views/admin/UserManagement.vue')
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const user = JSON.parse(localStorage.getItem('user') || '{}');
  const token = localStorage.getItem('token');
  const isAuthenticated = !!token;
  const isAdmin = user.role === 'admin';

  console.log('路由守卫检查:', {
    to: to.path,
    isAuthenticated,
    isAdmin,
    user
  });

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      console.log('未登录，重定向到登录页');
      next({
        path: '/',
        query: { redirect: to.fullPath }
      });
    } else if (to.matched.some(record => record.meta.requiresAdmin) && !isAdmin) {
      console.log('非管理员访问管理员页面，重定向到用户面板');
      next('/dashboard/drugs');
    } else {
      console.log('权限验证通过，允许访问');
      next();
    }
  } else {
    console.log('无需验证，允许访问');
    next();
  }
});

export default router;